import React, { useEffect, useState, useLayoutEffect } from "react";
import {
	Button,
	Select,
	Input,
	DatePicker,
	Dropdown,
	Menu,
	Space,
	Popover,
	Image,
	Typography,
	Form,
	InputNumber,
	message,
	Popconfirm
} from "antd";
import { goodsSpuMatch, updateOrderMatchOp, foreignOrdinarySearchByUrl, changeGoodsSkuMatch } from "../service";
import CommonZjfImg from "@/views/components/CommonZjfImg";

export const useSupplierList = ({ isOrderGoods, orderIds, selectedRows, image, spuId, skuId, goodsSkuMatches, isChangeMatch, matchedId, onDrawerClose }) => {
	const [dataSource, setDataSource] = useState([]); //
	const tableKey = "SystemGoodsMatchSkuIntelligentMatchTableSupplier";
	const matchedSupplierSkuIds = goodsSkuMatches?.map(e => String(e.supplierSkuId)) || [];
	useEffect(() => {
		foreignOrdinarySearchByUrl({ url: image }).then(res => {
			const { type, ordinarySearchMatchingGoodsVOS } = res.data || {};
			// type	0:成功,1:未搜索出类似图片
			console.log("getSearchUrlRes", ordinarySearchMatchingGoodsVOS);
			setDataSource(Array.isArray(ordinarySearchMatchingGoodsVOS) ? ordinarySearchMatchingGoodsVOS : []);
		});
	}, []);

	// 更换匹配：组装api和入参
	const getChangeMatchApiConfig = (TEXT, record) => {
		const API_DATA = {
			id: matchedId,
			matchType: 1,
			supplierId: record.storeId,
			supplierName: record.storeName,
			supplierSkuId: record.goodsId,
			// "supplierSkuImage": "128*68纯棉床笠",
			supplierSkuName: record.goodsName,
			supplierSkuPrice: record.vipPrice || record.goodsPrice,
			supplierSkuSpecs: record.goodsColor + ";" + record.goodsSize,
			supplierSpuCode: record.goodsCommonid
		};

		const MATCH_API = changeGoodsSkuMatch;
		return { API_DATA, MATCH_API };
	};
	// 添加匹配：组装api和入参
	const getAddMatchApiConfig = (TEXT, record) => {
		const API_DATA = {
			ids: [spuId],
			list: [
				{
					// 系统sku
					skuId,
					// 供应商sku
					supplierId: record.storeId,
					supplierName: record.storeName,
					supplierSkuId: record.goodsId,
					supplierSkuImage: record.goodsImage,
					supplierSkuName: record.goodsName
				}
			],
			type: 2 //关联类型 1：供应商 2：供应商商品
		};

		const MATCH_API = goodsSpuMatch;
		return { API_DATA, MATCH_API };
	};
	const handleCommand = (TEXT, record) => {
		if(isOrderGoods){
      return handleCommandFromOrder(record);//订单来源的操作
		}
		// 根据 isChangeMatch 获取 不同的api 和 data;
		let config, pre;
		if (isChangeMatch) {
			config = getChangeMatchApiConfig(TEXT, record);
			pre = "更换";
		} else {
			config = getAddMatchApiConfig(TEXT, record);
			pre = "";
		}
		const { MATCH_API, API_DATA } = config || {};

		// 执行api
		MATCH_API(API_DATA)
			.then(res => {
				const { success, data, msg } = res;
				if (success) {
					onDrawerClose(selectedRows[0]?.orderIds);
					message.success(msg || pre + "匹配成功");
				} else {
					message.warning(msg || pre + "匹配失败");
				}
			})
			.catch(err => {
				console.error(err);
				message.warning(pre + "匹配接口请求失败");
			});
	};

	//系统订单页面的单个智能匹配
	const handleCommandFromOrder = (record) => {
		console.log(isOrderGoods, orderIds, record, skuId)
		const API_DATA = {
			orderIds,
			skuId,
			// 供应商sku
			supplierId: record.storeId,
			supplierName: record.storeName,
			supplierSkuId: record.goodsId,
			supplierSkuImage: record.goodsImage,
			supplierSkuName: record.goodsName,
		};
		updateOrderMatchOp(API_DATA)
			.then(res => {
				const { success, data, msg } = res;
				if (success) {
					onDrawerClose(orderIds);
					message.success(msg || "匹配成功");
				} else {
					message.warning(msg || "匹配失败");
				}
			})
			.catch(err => {
				console.error(err);
				message.warning("匹配接口请求失败");
			});
	};
	const columns = [
		{
			name: "供应商名称",
			code: "storeName",
			width: 300
		},
		{
			name: "档口号",
			code: "shopCode",
			width: 160
		},
		{
			name: "图片",
			code: "goodsImage",
			width: 60,
			render: (value, record) => <CommonZjfImg img={record.goodsImage} storeId={record.storeId} />
		},
		{
			name: "商品名称",
			code: "goodsName",
			width: 300
		},
		{
			name: "款式编码",
			code: "goodsCommonId",
			width: 160
		},
		{
			name: "商品编码",
			code: "goodsId",
			width: 160
		},

		{
			name: "颜色",
			code: "goodsColor",
			width: 160
		},
		{
			name: "尺码",
			code: "goodsSize",
			width: 160
		},

		{
			name: "商城价（元）",
			code: "goodsPrice",
			align: "center",
			render: v => <span className="not-red">{v && `￥${Number(v).toFixed(2)}`}</span>
		},
		{
			lock: true,
			code: "action",
			width: 80,
			name: "操作",
			align: "center",
			render(_, record) {
				return (
					<>
						{matchedSupplierSkuIds.includes(String(record.goodsId)) ? (
							<span>已匹配</span>
						) : (
							<Popconfirm
								placement="leftTop"
								title="是否确定匹配？"
								onConfirm={() => {
									handleCommand("匹配", record);
								}}
								onCancel={() => {}}
							>
								<Button type="link">匹配</Button>
							</Popconfirm>
						)}
					</>
				);
			}
		}
	];

	const searchSimpleTableProps = {
		tableKey,
		rowKey: "id",
		// ///
		dataSource,
		columns,
		footer: false
	};

	return {
		tableKey,
		searchSimpleTableProps,
		dataSource
	};
};
